/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package cn.eclass.servlet.admin;

import cn.eclass.bean.api.IGiftOrderBean;
import cn.eclass.entity.GiftOrderEntity;
import cn.eclass.servlet.ActionFace;
import cn.eclass.utils.BeanFactory;
import cn.eclass.utils.Helper;
import com.google.gson.Gson;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;

/**
 *
 * @author fortruth
 */
public class Giftorder extends ActionFace {

    IGiftOrderBean bean = BeanFactory.factory.getGiftOrder();

    @Override
    public void doIndex() {
        try {
            List<GiftOrderEntity> entities = bean.list();

            Field[] fields = GiftOrderEntity.class.getDeclaredFields();
            List<HashMap<String, String>> theFields = Helper.buildField(fields, module);

            request.setAttribute("entities", entities);
            request.setAttribute("fields", theFields);
            request.getRequestDispatcher(tableView).forward(request, response);
        } catch (ServletException ex) {
            Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Admin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void doCreate() {
        GiftOrderEntity entity = new GiftOrderEntity();
        bean.add(form2Entity(entity));
        this.doIndex();
    }

    /*
     * ajax action
     */
    public void doSelect() {
        int id = Integer.valueOf(request.getParameter("id"));
        GiftOrderEntity entity = bean.get(id);
        out.print(new Gson().toJson(entity));
    }

    public void doUpdate() {
        int id = Integer.valueOf(request.getParameter("id"));
        GiftOrderEntity entity = bean.get(id);
        bean.update(form2Entity(entity));
        this.doIndex();
    }

    public void doDelete() {
        int id = Integer.valueOf(request.getParameter("id"));
        bean.delete(id);
        this.doIndex();
    }

    private GiftOrderEntity form2Entity(GiftOrderEntity entity) {
        entity.setGiftId(Integer.valueOf(request.getParameter("giftId")));
        entity.setUserId(Integer.valueOf(request.getParameter("userId")));
        entity.setDescription(request.getParameter("description"));
        entity.setValid(Integer.parseInt(request.getParameter("valid")));
        return entity;
    }
}
